package com.guomao.controller;

import com.guomao.entity.Order;
import com.guomao.entity.Result;
import com.guomao.mapper.OrderMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Collection;

@Controller
public class MyControllerB {

    @Autowired
    private OrderMapper orderMapper;

    @RequestMapping("/")
    public String toIndex() {
        return "forward:/order";
    }

    @GetMapping("/order")
//    public Collection<Order> getAllOrders() {
    public String getAllOrders(Model m) {
        Collection<Order> orders = orderMapper.getAllOrders();
        m.addAttribute("orders", orders);
        return "index";
    }

    @GetMapping("/order/{id}")
    public Order getOrderById(@PathVariable("id") Integer id) {
        return orderMapper.getOrderById(id);
    }

    @DeleteMapping("/order/{id}")
    public String deleteOrderById(@PathVariable("id") Integer id) {
        orderMapper.deleteOrderById(id);
        return "redirect:/order";
    }

    //RequestBody 读取json格式
 /*   @PostMapping("/order")
    public String addOrder(Order order) {
        System.out.println(">>>>>>>>>>>" + order);
        orderMapper.updateOrder(order);
        return "redirect:/order";
    }*/


    @PostMapping("/order")
    @ResponseBody
    public Result addOrder(@RequestBody Order order) {
        System.out.println(">>>>>>>>>>>" + order);
        orderMapper.updateOrder(order);
        return new Result("新增成功", 200);
    }

    @PutMapping("/order")
//    public String updateOrder(@RequestBody Order order) {
    public String updateOrder(Order order) {
        orderMapper.updateOrder(order);
        return "redirect:/order";
    }

    @GetMapping("/toUpdate/{id}")
    public String toUpdate(@PathVariable("id") Integer id, Model m) {
        Order order = orderMapper.getOrderById(id);
        m.addAttribute("order", order);
        return "update";
    }
}
